package com.ruoyi;



import com.alibaba.excel.util.StringUtils;
import com.alibaba.excel.write.handler.context.CellWriteHandlerContext;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.*;

/**
 * 单元格样式处理器
 *
 * @author by liangzj
 * @since 2022/9/17 16:26
 */
public class StyleWriteHandler extends LongestMatchColumnWidthStyleStrategy {

    @Override
    public void afterCellDispose(CellWriteHandlerContext context) {
        if (context.getHead()) { // 表头属性设置
            headerStyle(context);
        } else { // 表数据属性设置
            //            contentStyle(context);
            contentStyle2(context.getCell());
        }
    }

    /**
     * 解锁没有内容的单元格(方法1)
     *
     * @param context
     */
    private void contentStyle(CellWriteHandlerContext context) {
        WriteCellStyle writeCellStyle = context.getFirstCellData().getOrCreateStyle();
        /* !! 注意：这行就是解锁单元格的代码，locked == true为锁定，locked == false为不锁定 */
        writeCellStyle.setLocked(StringUtils.isNotBlank(context.getCell().getStringCellValue()));

        // 如果锁定，置灰(这行只是设置样式，不重要)
        if (writeCellStyle.getLocked()) {
            WriteFont writeFont = new WriteFont();
            writeFont.setColor(IndexedColors.GREY_40_PERCENT.index);
            writeCellStyle.setWriteFont(writeFont);
        }
    }

    /**
     * 解锁没有内容的单元格(方法2)
     *
     * @param cell
     */
    private void contentStyle2(Cell cell) {
        // 创建一个新的单元格样式
        CellStyle cellStyle = cell.getSheet().getWorkbook().createCellStyle();
        // 复制原来单元格的样式(这样就能保证原来单元格的样式不丢失)
        cellStyle.cloneStyleFrom(cell.getCellStyle());
        /* !! 注意：这行就是解锁单元格的代码，locked == true为锁定，locked == false为不锁定 */
        cellStyle.setLocked(StringUtils.isNotBlank(cell.getStringCellValue()));
        // 把新建的样式设置为当前单元格样式
        cell.setCellStyle(cellStyle);

//        // 如果锁定，置灰(样式设置，不重要)
//        if (cell.getCellStyle().getLocked()) {
//            Font font = cell.getSheet().getWorkbook().createFont();
//            font.setColor(IndexedColors.GREY_40_PERCENT.index);
//            cellStyle.setFont(font);
//        }
    }

    /**
     * 表头格式处理
     *
     * @param context
     */
    private static void headerStyle(CellWriteHandlerContext context) {
        Cell cell = context.getCell();

        int colWidth = cell.getStringCellValue().length() * 1500;
        boolean needHidden = "requireId".equals(cell.getStringCellValue());

        // 根据表头文字设置列宽
        cell.getSheet().setColumnWidth(cell.getColumnIndex(), colWidth);
        // 冻结表头
        cell.getSheet().createFreezePane(1, 2);
        // 隐藏指定列
        cell.getSheet().setColumnHidden(cell.getColumnIndex(), needHidden);
    }


    public static void WriteExcelByPoi(String fileData) throws Exception,
            InvalidFormatException {
        try {
            InputStream in = new FileInputStream(new File("d:/code/22.xlsx"));

            Workbook workbook = new XSSFWorkbook(in);
            org.apache.poi.ss.usermodel.Sheet sheet = (org.apache.poi.ss.usermodel.Sheet)workbook.getSheetAt(1);
            sheet.protectSheet(""); //设置表单保护密码


            org.apache.poi.ss.usermodel.Row row = null;
            org.apache.poi.ss.usermodel.Cell cell = null;

            String cellValue = "132700002800";
            XSSFCellStyle alterableStyle = (XSSFCellStyle)workbook.createCellStyle(); //获取当前单元格的样式对象
            alterableStyle.setLocked(true);    //设定此单元格为锁定状态
            XSSFCellStyle nolockedStyle = (XSSFCellStyle)workbook.createCellStyle(); //获取当前单元格的样式对象
            nolockedStyle.setLocked(false);    //设定此单元格为非锁定状态

            String value = "非锁定";

            for (int i = 0; i < 5; i++) {
                System.out.println(" i =" + i);
                row = sheet.createRow(i);
                cell = row.createCell(0);
                cell.setCellValue(cellValue);
                cell.setCellStyle(alterableStyle);
                cell = row.createCell(1);
                cell.setCellValue(value);
                cell.setCellStyle(nolockedStyle);
            }

            in.close();

            FileOutputStream out = null;
            try {
                out = new FileOutputStream(fileData);
                workbook.write(out);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
